<template>
  <div class="add_content">

    <div v-if="!showById" class="add_operation">
      <el-button size="small" @click="add"><el-icon><Plus /></el-icon></el-button>
    </div>
    <div
      v-for="(item, index) in objectList"
      :key="index"
      class="add_item"
    >{{ item.name }}
      <span class="add_item_weight">
        <el-icon><Odometer /></el-icon>
        {{ item.weight }}g <span v-if="showUnit" class="add_item_unit">/100g</span>
      </span>
      <span v-if="!showById" class="add_item_del" @click="del(index)">
        <el-icon><Close /></el-icon>
      </span>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="`添加${titleName}`"
      width="80%"
      :before-close="handleClose"
    >
      <el-form
        ref="listFormRef"
        :model="listForm"
        label-width="200px"
      >
        <el-form-item :label="titleName" prop="objectId" :rules="[{ required: true, message: '请选择' }]">
          <el-select
            v-model="listForm.objectId"
            placeholder="请选择"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in dataList"
              :key="item.id"
              :label="item[searchKey]"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="`重量${showUnit ? '(每100g含有多少g)' : '(g)'}`" prop="weight" :rules="[{ required: true, message: '请输入' }]">
          <el-input v-model="listForm.weight" maxlength="9" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog_footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineProps, watch, computed } from 'vue'
import { Plus, Close, Odometer } from '@element-plus/icons-vue'
import { queryAllElementList, queryAllIngredientList, queryAllQuestionList } from './api.js'

const props = defineProps({
  queryType: {
    type: String,
    default: 'element'
  },
  modelValue: {
    type: String,
    default: ''
  },
  showById: {
    type: String,
    default: ''
  },
  showUnit: {
    type: Boolean,
    default: true
  }
})

const objectList = ref([])
const dataList = ref([])
const dialogVisible = ref(false)
const listForm = ref({
  objectId: '',
  weight: ''
})
const listFormRef = ref(null)
const searchKey = computed(() => {
  const map = {
    'question': 'content',
    'user': 'user_name',
    'element': 'name',
    'ingredient': 'name',
    'recipe': 'name'
  }
  return map[props.queryType] || 'name'
})
const titleName = computed(() => {
  const map = {
    'question': '问题',
    'user': '用户',
    'element': '元素',
    'ingredient': '食材',
    'recipe': '食谱'
  }
  return map[props.queryType]
})

const emit = defineEmits(['update:modelValue', 'input'])

watch(() => props.modelValue, (newVal, oldVal) => {
  initData(newVal)
}, { immediate: false })

watch(objectList, (newVal, oldVal) => {
  const list = newVal.map(item => ({
    id: item.id,
    weight: item.weight
  }))
  if (!props.showById) emit('update:modelValue', JSON.stringify(list))
}, { deep: true })

onMounted(() => {
  switch (props.queryType) {
    case 'element':
      queryAllElementList().then(res => {
        getValue(res.result)
        initData(props.modelValue)
      })
      break
    case 'ingredient':
      queryAllIngredientList().then(res => {
        dataList.value = res.result
        initData(props.modelValue)
        // 反显含量
        if (props.showById) {
          const data = []
          dataList.value.forEach(row => {
            // 当前食材的元素含量列表
            if (!row.nutrition_list) return
            const list = JSON.parse(row.nutrition_list)
            // 根据含量列表找到对应食材的当前元素的含量
            const rowObj = list.find(item => item.id === props.showById)
            if (rowObj) {
              const showInfo = getItem({
                id: row.id,
                weight: rowObj.weight
              })
              data.push(showInfo)
            }
          })
          objectList.value = data
        }
      })
      break
    case 'question':
      queryAllQuestionList().then(res => {
        getValue(res.result)
        initData(props.modelValue)
      })
      break
  }
})

const initData = (value) => {
  if (value) {
    const list = JSON.parse(value)
    if (Array.isArray(list)) {
      const objList = []
      list.forEach(row => {
        if (props.queryType === 'element') {
          // 元素会带有含量信息
          objList.push(getItem(row))
          objectList.value = objList
        } else if (props.queryType === 'ingredient') {
          // 食材不会带有含量信息, 需要额外计算含量
          objList.push(getItem(row))
          objectList.value = objList
        } else if (props.queryType === 'recipe') {
          // 食谱
        }
      })
    }
  } else {
    objectList.value = []
  }
}

const getValue = (data) => {
  if (props.modelValue) {
    const list = JSON.parse(props.modelValue)
    // 将id列表转换为对象列表
    if (Array.isArray(list)) {
      const objList = []
      list.forEach(row => {
        const obj = data.find(item => item.id === row)
        if (obj) {
          objList.push(obj)
        }
      })
      objectList.value = objList
    }
  }
  dataList.value = data
}

const add = () => {
  dialogVisible.value = true
}

const handleClose = () => {
  dialogVisible.value = false
}

const del = (index) => {
  objectList.value.splice(index, 1)
}

const submit = () => {
  listFormRef.value.validate((valid) => {
    if (valid) {
      objectList.value.push(getItem({
        id: listForm.value.objectId,
        weight: listForm.value.weight
      }))
      dialogVisible.value = false
      // 恢复数据
      // 清空校验
      listFormRef.value.resetFields()
    }
  })
}

const getItem = ({ id, weight }) => {
  const obj = dataList.value.find(item => item.id === id)
  if (!obj) return { name: '未知', weight, id }
  console.log(obj, '==obj=========>')
  const name = obj[searchKey.value || 'name']
  return {
    name,
    weight,
    id
  }
}

</script>

<style lang="scss" scoped>
.add_content {
  width: 100%;
  height: 150px;
  border-bottom: 1px solid #e2e2e2;
  border-radius: 5px;
  overflow-y: auto;
  // box-sizing: border-box;
  .add_operation {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 5px;
  }

  .add_item {
    width: 100%;
    line-height: 32px;
    padding: 0 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-bottom: 2px;
    text-align: left;
    box-sizing: border-box;

    .add_item_weight {
      display: inline-block;
      margin-left: 10px;

      ::v-deep .el-icon {
        transform: translateY(2px);
        color: gray;
      }

      .add_item_unit {
        color: rgb(206, 206, 206);
      }
    }

    .add_item_del {
      float: right;
      cursor: pointer;
      line-height: 36px;
      height: 32px;
    }
  }
}
::v-deep .dialog_footer {
  display: flex;
}
</style>